const path = require('path');
const glob = require('glob');
const sequelize = require('@/db/seq');

// 使用 glob 同步加载所有模型文件
const modelFiles = glob.sync('**/*.js', {
  cwd: __dirname,
  ignore: ['index.js', '**/associations.js']
});

const models = modelFiles.reduce((acc, filePath) => {
  const fullPath = path.join(__dirname, filePath);
  const model = require(fullPath);
  
  // 处理模型导出
  if (model && model.name) {
    acc[model.name] = model;
  } else if (model && typeof model === 'object') {
    Object.assign(acc, model);
  }
  
  return acc;
}, {});

// 自动注册关联关系
Object.values(models).forEach(model => {
  if (typeof model.associate === 'function') {
    model.associate(models);
  }
});

module.exports = {
  ...models,
  sequelize,
};